package jrain.fw.http.tomcat;

import java.io.File;
import java.util.HashMap;
import java.util.concurrent.atomic.AtomicBoolean;

import org.apache.catalina.Context;
import org.apache.catalina.startup.Tomcat;

import jrain.fw.core.log.Logger;
import jrain.fw.core.log.LoggerFactory;
import jrain.fw.core.service.ServiceConst;
import jrain.fw.core.utils.FwUtils;
import jrain.fw.http.common.consts.HttpConsts;
import jrain.fw.http.common.servlet.DispatcherServlet;
import jrain.utils.collection.RDMap;
import jrain.utils.collection.RMap;
import jrain.utils.lang.LangUtils;

public class HttpTomcatServer {

	private static final AtomicBoolean init = new AtomicBoolean(false);
	private static volatile Tomcat tomcat;
	private static final Logger log = LoggerFactory.getLogger("http-server-tomcat");

	public void start() throws Exception {
		if (!init.getAndSet(true)) {
			RMap<String, Object> cfg = FwUtils.getCfgService().getCfgMap(ServiceConst.M_HTTP_SERVER, new RDMap<>(new HashMap<>()));
			int port = LangUtils.parseInt(cfg.get(TomcatCfg.httpTomcatPort.getName()));
			//从配置文件加载，用于支持一个服务器部署不同端口
			if(port == 0){
				port = LangUtils.parseInt(FwUtils.getFwCfg().get(TomcatCfg.httpTomcatPort.getName()));
			}
			if(port == 0){
				port = TomcatCfg.httpTomcatPort.getIntValue();
			}
			String baseDir = new File(System.getProperty("java.io.tmpdir")).getAbsolutePath();
			tomcat = new Tomcat();
			tomcat.setBaseDir(baseDir);
			tomcat.setPort(port);
			tomcat.getConnector().setProperty("URIEncoding", "UTF-8");
			tomcat.getConnector().setProperty("connectionTimeout", "60000");
			tomcat.getConnector().setProperty("maxKeepAliveRequests", "-1");
			tomcat.getConnector().setProtocol("org.apache.coyote.http11.Http11NioProtocol");
			tomcat.getConnector().setProperty("disableUploadTimeout", "false");
			Context context = tomcat.addContext("", baseDir);
			Tomcat.addServlet(context, "dispatcher", new DispatcherServlet());
			context.addServletMappingDecoded("/*", "dispatcher");
			tomcat.start();
			log.info("{} tomcat started,port={}!", HttpConsts.S_HTTP_SERVER_SERVICE, port);
			tomcat.getServer().await();
		}
	}

	public void stop() throws Exception {
		if (init.get()) {
			if (tomcat != null) {
				tomcat.stop();
			}
			init.set(false);
		}
	}

	public static void main(String[] args) {
		try {
			new HttpTomcatServer().start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}